package cn.cloudplug.friendsrecommend;

import java.util.ArrayList;
import java.util.List;



import cn.cloudplug.friendsrecommend.R;
import cn.cloudplug.friendsrecommend.adapter.MyListAdapter;
import cn.cloudplug.friendsrecommend.entity.MySelfInfomation;
import cn.cloudplug.friendsrecommend.entity.Race;
import cn.cloudplug.friendsrecommend.util.Constant;
import cn.cloudplug.friendsrecommend.util.GetPhotoUtil;
import cn.cloudplug.friendsrecommend.view.CircleImageView;
import cn.cloudplug.friendsrecommend.view.LeftMenu;
import cn.cloudplug.friendsrecommend.view.ReflashListView;
import cn.cloudplug.friendsrecommend.view.RightMenu;
import cn.cloudplug.friendsrecommend.view.ReflashListView.IReflashListener;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final String TAG="MainActivity";
	public MySelfInfomation me;
	private LeftMenu lMenu;
	private RightMenu rMenu;
	private boolean isExists;
	private ReflashListView listView;
	private List<Race> testData;
	private MyListAdapter adapter;
	private MyReceiver myReceiver;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.UPDATE_UI:
				updateUI();
				break;
			case Constant.CHANGE_PHOTO:
				changePhoto();
			}
		}
	};
	private ImageView iv_lMenu;
	private ImageView iv_rMenu;
	private LinearLayout layout_banner;
	private int bannerImgs[] = { R.drawable.banner1, R.drawable.banner2,
			R.drawable.banner3 };
	private int listImgs[] = { R.drawable.list1, R.drawable.list2,
			R.drawable.list3, R.drawable.list4, R.drawable.list5,
			R.drawable.list6, R.drawable.list8 };
	private boolean isScroller = true;
	private ViewPager bannerViewPager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setView();
	}
	
	protected void changePhoto() {
		iv_lMenu.setImageBitmap(lMenu.change.photo);
		lMenu.iv_photo.setImageBitmap(lMenu.change.photo);
	}

	private void setView() {
		
		layout_banner=(LinearLayout) findViewById(R.id.layout_banner);
		
		iv_lMenu = (CircleImageView) findViewById(R.id.iv_left_menu);
		iv_lMenu.setImageResource(R.drawable.cloud_default_photo_meal);
		iv_rMenu = (ImageView) findViewById(R.id.iv_right_menu);

		lMenu = new LeftMenu(this);
		rMenu = new RightMenu(this);
		
		iniBannerImageView();
		getTestData();
		iniListView();
		
		initBannerViewPager();
		initBannerThread();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		myReceiver=new MyReceiver();
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constant.LOGIN_SUCCESS);
		registerReceiver(myReceiver, filter);
		SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE);
		Editor editor=sp.edit();
		editor.putBoolean("isLogin", false);
		editor.commit();
	}
	
	

	protected void updateUI() {
		SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE);
		Editor editor=sp.edit();
		editor.putBoolean("isLogin", true);
		editor.commit();
		Log.i(TAG, "isLogin"+true);
		lMenu.unLogin.setVisibility(View.GONE);
		lMenu.logined.setVisibility(View.VISIBLE);
		lMenu.iv_photo.setImageResource(R.drawable.cloud_meal);
		iv_lMenu.setImageResource(R.drawable.cloud_meal);
		lMenu.tv_name.setText("我就是贝壳汉姆");
		lMenu.updateUI();
	}
	
	private void iniListView() {
		listView = (ReflashListView) findViewById(R.id.reflashListView1);
		listView.setDividerHeight(0);
		adapter = new MyListAdapter(this, testData, handler);
		listView.setAdapter(adapter);


		iv_lMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				lMenu.showMenu();
			}
		});
		iv_rMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				rMenu.showMenu();
			}
		});
		listView.setInterfacs(new IReflashListener() {
			@Override
			public void onReflash() {
				new AsyncTask<Void, Void, Void>() {
					@Override
					protected Void doInBackground(Void... params) {
						SystemClock.sleep(2000);
						for (int i = 0; i < 2; i++) {
							Race race = new Race();
							race.setImageId(listImgs[i]);
							race.setId(i);
							race.setFavorite(2000 + i * 100 + i * 10);
							race.setIsfocus(i / 2 == 0 ? true : false);
							testData.add(0, race);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						adapter.notifyDataSetChanged();
						listView.reflashComplete();
						listView.scrollTo(0, 30);
					}
				}.execute(new Void[] {});
			}

			@Override
			public void onLoad() {
				new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						SystemClock.sleep(2000);
						for (int i = 0; i < 2; i++) {
							Race race = new Race();
							race.setImageId(listImgs[i]);
							race.setId(i);
							race.setFavorite(3000 + i * 100 + i * 10);
							race.setIsfocus(i / 2 == 0 ? true : false);
							testData.add(race);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						adapter.notifyDataSetChanged();
						listView.loadingComplete();
					}
				}.execute(new Void[] {});
			}
		});
		
	}


	
	private void getTestData() {
		testData = new ArrayList<Race>();
		for (int i = 0; i < 5; i++) {
			Race race = new Race();
			race.setId(i);
			race.setImageId(listImgs[i]);
			race.setFavorite(1000 + i * 100);
			race.setIsfocus(i / 2 == 0 ? true : false);
			testData.add(race);
		}
	}

	private void initBannerThread() {
		final Handler h = new Handler();
		h.postDelayed(new Runnable() {
			@Override
			public void run() {
				bannerViewPager.setCurrentItem(bannerViewPager.getCurrentItem() + 1);
				if (isScroller) {
					h.postDelayed(this, 3000);
				}
			}
		}, 3000);
	}

	private  void iniBannerImageView() {
		LinearLayout.LayoutParams params;
		for(int i=0;i<bannerImgs.length;i++){
		 View dot = new View(this);
		 dot.setBackgroundResource(R.drawable.point_background);
		 params = new LayoutParams(20, 20);
		 params.rightMargin = 10;
		 dot.setLayoutParams(params);
		 dot.setEnabled(false);
		 layout_banner.addView(dot);
		}
		
	}

	private int previousPointEnale=0;
	private void initBannerViewPager() {
		bannerViewPager = (ViewPager) findViewById(R.id.bannerViewPagerId);
		bannerViewPager.setAdapter(new BannerAdapter());
		bannerViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int pos) {
				int newPosition = pos % bannerImgs.length;
				layout_banner.getChildAt(previousPointEnale).setEnabled(false);
				layout_banner.getChildAt(newPosition).setEnabled(true);
				previousPointEnale=newPosition;
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int responseCode,Intent data) {
		if (data != null) {
			switch (requestCode) {
			case Constant.PICK:
			case Constant.CAMERA:
			case Constant.NOT_NULL:
				lMenu.change.getPhoto(requestCode, data);
				Message.obtain(handler, Constant.CHANGE_PHOTO).sendToTarget();
				break;
			}
		} 
		super.onActivityResult(requestCode, responseCode, data);
	}
	@Override
	public void onBackPressed() {
		if (!isExists) {
			Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
			isExists = true;
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					isExists = false;
				}
			}, 3000);
		} else {
			unregisterReceiver(myReceiver);
			super.onBackPressed();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		isScroller = false;
	}

	class BannerAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			return 1000;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((ImageView) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			ImageView mImageView = new ImageView(MainActivity.this);
			mImageView.setScaleType(ScaleType.FIT_XY);
			mImageView
					.setImageResource(bannerImgs[position % bannerImgs.length]);
			mImageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent();
					intent.setClass(MainActivity.this, RaceInfoActivity.class);
					startActivity(intent);
				}
			});
			container.addView(mImageView);
			return mImageView;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}
	
	class MyReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			String order=intent.getAction();
			if(order.equals(Constant.LOGIN_SUCCESS)){
				me=(MySelfInfomation) intent.getSerializableExtra("MySelfInfomation");
				Message.obtain(handler, Constant.UPDATE_UI).sendToTarget();
			}
		}
		
	}
}